package pes

import (
	"sync"

	"gitee.com/linxing_3/sr-core/config"
	"gitee.com/linxing_3/sr-core/plugins/es"
	"gitee.com/linxing_3/sr-core/relay"
	"gitee.com/mkwchecking/sr-admin/pkg/instance"
)

var esLock = &sync.Mutex{}

func UpsertES() (es.IEsClient, error) {
	esLock.Lock()
	defer esLock.Unlock()
	cli, err := instance.GetOrInit(es.YESKey{}, initES)
	if err != nil {
		return nil, err
	}
	return *cli, nil
}

func initES() (es.IEsClient, error) {
	if cli := es.FromCtx(relay.Context()); cli != nil {
		return cli, nil
	}

	cli, err := es.Install(config.Get().ES)
	if err != nil {
		return nil, err
	}

	return cli, nil
}
